home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Tech Arsenal 1
/
Tech Arsenal (Arsenal Computer).ISO
/
tek-01
/
castools.zip
/
NEWPHONE.C
< prev
next >
Wrap
Text File
|
1990-01-02
|
3KB
|
107 lines
/*
NEWPHONE.C Function PbCreatePhonebook: creates a new phonebook file.
This function creates a phonebook file according to the format described in
the CAS document.
INPUT: Name to give new phonebook file, and optionally a pointer to a
phonebook structure.
OUTPUT: If a phonebook structure was provided on input, it is filled with
the new phonebook's data.
*/
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
#include <memory.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <io.h>
#include <phonebk.h>
#include <pbdflt.h>
PB * pascal PbCreatePhonebook(PB *pb,
char *name)
{
PB *NewPb;
struct stat filestat; /* for call to stat(), in case file already exists */
int writ, /* for return from fwrite() */
result; /* for return from stat() */
long *dummy;
Pberrno = 0; /* Initially, always reset */
/* First, check params */
if (name == NULL) {
Pberrno = INVALIDPARAMETER;
return(NULL);
}
/* Check for any file by the same name as the proposed new phonebook */
result = stat(name, &filestat);
if (!result) {
Pberrno = FILEALREADYEXISTS;
return(NULL);
}
/* If a phonebook structure provided, use it; otherwise allocate one */
if (!pb) {
NewPb = (PB *)calloc(1, sizeof(PB));
if (!NewPb) {
Pberrno = OUTOFMEM;
return(NULL);
}
}
else {
NewPb = pb;
}
/* Copy the default header into the new phonebook's header field */
memcpy(&NewPb->header, &DefaultPbHeader, sizeof(PBH));
/* Create and open for reading and writing the new phonebook file */
NewPb->fp = fopen(name, "w+b");
if (!NewPb->fp) {
Pberrno = CANTOPEN;
if (!pb) {
free(NewPb);
}
return(NULL);
}
/* Write the new phonebook's header and offsets array to the file */
writ = fwrite(&NewPb->header, sizeof(PBH), 1, NewPb->fp);
if (writ != 1) {
Pberrno = CANTWRITE;
fclose(NewPb->fp);
if (!pb) {
free(NewPb);
}
return(NULL);
}
dummy = (long *)calloc(1000, sizeof(long));
if (!dummy) {
Pberrno = OUTOFMEM;
fclose(NewPb->fp);
if (!pb) {
free(NewPb);
}
return(NULL);
}
writ = fwrite(dummy, sizeof(long), 1000, NewPb->fp);
free(dummy);
if (writ != 1000) {
Pberrno = CANTWRITE;
fclose(NewPb->fp);
if (!pb) {
free(NewPb);
}
return(NULL);
}
return(NewPb); /* And that's all! */
}